import 'package:pacsun/components/appbar.dart';
import 'package:pacsun/view/create/createBecomeCreator.dart';
import 'package:pacsun/view/task/theme/app_colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pacsun/services/socialMediaConnectService.dart'
    show TikTokConnect;
import 'package:pacsun/widgets/toastMenu.dart' show ToastMenu;
import 'package:pacsun/provider/userProv.dart' show UserProvider;
import 'package:provider/provider.dart';

class sharePage extends StatelessWidget {
  final BecomeCreatorController becomeController;
  const sharePage({super.key, required this.becomeController});

  //final _controller = BecomeCreatorController();

  Future<void> _connectTikTok(BuildContext context) async {
    try {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) => const Center(child: CircularProgressIndicator()),
      );

      final oauthUrl = await TikTokConnect().getOauth2SSO();

      // 接收完整的回调URL字符串
      final callbackUrl = await Navigator.of(context).push<String>(
        MaterialPageRoute(
          fullscreenDialog: true,
          builder: (_) => TikTokAuthWebView(initialUrl: oauthUrl),
        ),
      );

      if (callbackUrl != null) {
        // 解析URL获取code
        final uri = Uri.parse(callbackUrl);

        final code = uri.queryParameters['code'];
        final scopes = uri.queryParameters['scopes'];

        if (code != null && scopes != null) {
          final openId =
              await TikTokConnect().exchangeCodeForOpenId(code, scopes);

          if (openId != null) {
            final _tikTokInfo = await TikTokConnect().getUserInfo(openId);

            Navigator.of(context).pop();
            print('Linked tiktok returned info: ${_tikTokInfo}');

            context
                .read<UserProvider>()
                .updateTiktokLinkStatus(context, openId);
          }

          becomeController.tiktokController.text = openId;

          Navigator.of(context).pop();
          ToastMenu.showToast(context, 'Linking to TikTok successfully!');

          //  showStoreFrontBottomSheet(context, 'tt');
        } else {
          Navigator.of(context).pop();
          throw Exception('Authorization code not found in callback URL');
        }
      } else {
        Navigator.of(context).pop();
        throw Exception('User canceled or authentication failed');
      }
    } catch (e) {
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        // SnackBar(content: Text('TikTok connection failed: ${e.toString()}')),
        SnackBar(content: Text('TikTok connection failed.')),
      );
    }
  }

  Widget build(BuildContext context) {
    return MediaQuery(
      data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling),
      child: Scaffold(
          backgroundColor: Colors.black,
          extendBodyBehindAppBar: true,
          appBar: CommonTransparentAppBar(
            title: 'Confirm authorization',
          ),
          body: Column(
            children: [
              Stack(children: [
                AppBarBg(
                  bgSrc:
                      'assets/imgs/share_page.png', //'assets/imgs/appCommonNavBarBg.png',
                  height: 230,
                  width: 375,
                  fit: BoxFit.cover,
                ),
                SafeArea(
                  child: Container(
                      width: 375.w,
                      padding: EdgeInsets.only(left: 98, right: 98, top: 53),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Image(
                            image: AssetImage("assets/imgs/pacsun.png"),
                            width: 60,
                          ),
                          Image(
                            image: AssetImage("assets/imgs/share.png"),
                            width: 40,
                          ),
                          Image(
                              image: AssetImage("assets/imgs/img_tiktok.png"),
                              width: 60)
                        ],
                      )),
                )
              ]),
              Expanded(
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.only(left: 27, top: 24, bottom: 24),
                  color: Color(0XFF222222),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                          "Connecting your social profiles allows PacSun to view your social insights that help evaluate your application.",
                          style: TextStyle(
                            color: Color(0XFFFFFFFF),
                            fontSize: 12.0,
                          )),
                    ],
                  ),
                ),
              ),
              Center(
                  child: GestureDetector(
                      onTap: () {
                        // 点击事件的处理逻辑
                        _connectTikTok(context);
                      },
                      child: Container(
                        width: double.infinity,
                        height: 55.0,
                        margin: EdgeInsets.only(
                            left: 20.0, top: 10.0, right: 20.0, bottom: 34),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: Color(0XFFD73030),
                          borderRadius: BorderRadius.circular(27.5), // 设置圆角半径
                        ),
                        child: Text('OK',
                            style: TextStyle(
                              color: Color(0XFFFFFFFF),
                              fontSize: 20.0,
                              fontWeight: FontWeight.w700,
                            )),
                      )))
            ],
          )),
    );
  }
}

class StepText extends StatelessWidget {
  final String step;
  final String text;
  const StepText({super.key, required this.step, required this.text});

  @override
  Widget build(BuildContext context) {
    return Row(
      spacing: 12.w,
      children: [
        Container(
          width: 17.w,
          height: 17.h,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Color(0XFFFFD20A),
            borderRadius: BorderRadius.circular(17).r,
          ),
          child: Text(
            step,
            style: customTextStyle(
              color: FamilyTextColor.black,
              fontWeight: 700,
            ),
          ),
        ),
        Text(
          text,
          style:
              customTextStyle(fontSize: 14, fontWeight: 600, height: 26 / 14),
        )
      ],
    );
  }
}
